package com.app.controller;

import com.app.common.Result;
import com.app.common.SystemConstant;
import com.app.service.UserService;
import com.app.util.FileTypeCheckerUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Random;

@Controller
@RestController
public class UploadController {
    private static final Pattern VALID_FILENAME_PATTERN = Pattern.compile("^[a-zA-Z0-9_.-]+$");

    // 定义支持的图片后缀
    private static final String[] IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".gif", ".bmp", ".tif", ".tiff", ".webp", ".svg", ".heif", ".heic"};
    // 定义支持的 PDF 后缀
    private static final String PDF_EXTENSION = ".pdf";
    // 定义支持的 Word 后缀
    private static final String[] WORD_EXTENSIONS = {".doc", ".docx", ".dot", ".dotx", ".dotm", ".docm"};


    // 判断字符串是否以图片后缀结尾
    public static boolean hasImageExtension(String filename) {
        if (filename == null || filename.isEmpty()) {
            return false;
        }
        for (String extension : IMAGE_EXTENSIONS) {
            if (filename.toLowerCase().endsWith(extension)) {
                return true;
            }
        }
        return false;
    }


    // 判断字符串是否以 PDF 后缀结尾
    public static boolean hasPdfExtension(String filename) {
        if (filename == null || filename.isEmpty()) {
            return false;
        }
        return filename.toLowerCase().endsWith(PDF_EXTENSION);
    }


    // 判断字符串是否以 Word 后缀结尾
    public static boolean hasWordExtension(String filename) {
        if (filename == null || filename.isEmpty()) {
            return false;
        }
        for (String extension : WORD_EXTENSIONS) {
            if (filename.toLowerCase().endsWith(extension)) {
                return true;
            }
        }
        return false;
    }

    @Autowired
    UserService userService;

    @Autowired
    private FileTypeCheckerUtil fileTypeCheckerUtil;

    /**
     * 上传文件
     */
    @PostMapping("/api/upload")
    public Result<String> upload(HttpServletRequest request,
                                 @RequestParam("file") MultipartFile file) throws IOException {

        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(500, "token不存在");
        }
        if (!FileTypeCheckerUtil.isAllowedFileType(file)) {
            return Result.error(500, "文件类型错误!");
        }
        //防止路径遍历
        String originalFileName = file.getOriginalFilename();
        if (!StringUtils.hasText(originalFileName) || !VALID_FILENAME_PATTERN.matcher(originalFileName).matches()) {
            return Result.error(500, "文件名不合法!");
        }

        if (!file.isEmpty()) {
            // 定义文件存储的基础路径
            String basePath = SystemConstant.DEFAULT_UPLOAD_URL;
            // 获取当前日期并格式化
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
            String datePath = sdf.format(new Date());
            // 构建完整的存储路径
            String filePathStr = basePath + datePath + "/";
            File filePath = new File(filePathStr);

            // 如果目录不存在，创建目录
            if (!filePath.exists()) {
                filePath.mkdirs();
            }
            // 获得上传文件名
            String fileName = file.getOriginalFilename();
            assert fileName!= null;
            int lastIndexOf = fileName.lastIndexOf(".");
            String date = getRandomString2(8);
            // 获取文件的后缀名.jpg
            String suffix = fileName.substring(lastIndexOf);
            filePath = new File(filePathStr + date + suffix);
            //将上传文件保存到一个目标文件中
            file.transferTo(filePath);
            String imgURL = "";
            //szjy.gshwsc.com  域名
            imgURL = SystemConstant.DEFAULT_UPLOAD_SERVICE_URL + date + suffix;
            return Result.success(imgURL);
        } else {
            return Result.error(500, "上传失败");
        }

    }

    //可以指定字符串的某个位置是什么范围的值
    public static String getRandomString2(int length) {
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(3);
            long result = 0;
            switch (number) {
                case 0:
                    result = Math.round(Math.random() * 25 + 65);
                    sb.append(String.valueOf((char) result));
                    break;
                case 1:
                    result = Math.round(Math.random() * 25 + 97);
                    sb.append(String.valueOf((char) result));
                    break;
                case 2:
                    sb.append(String.valueOf(new Random().nextInt(10)));
                    break;
            }


        }
        return sb.toString();
    }
}
